<template>
  <div ref="containerRef" class="container"></div>
</template>

<script setup lang="ts">
import LogicFlow from '@logicflow/core';
import '@logicflow/core/dist/style/index.css';
import { DndPanel } from '@logicflow/extension';
import '@logicflow/extension/lib/style/index.css';

import Entry from './action/Entry';
import BaseBehaviorConnection from './base/BaseBehaviorConnection';
import BehaviorTreeAdapter from './core/Adapter';
import BehaviorDesigner from './core/BehaviorDesigner';
import ConnectionManager from './core/ConnectionManager';
import SceneManager from './core/SceneManager';

LogicFlow.use(DndPanel);
LogicFlow.use(BehaviorTreeAdapter);

defineOptions({
  name: 'BehaviorDesignerIndex',
});

const emits = defineEmits(['nodeSelected']);

const containerRef = ref<HTMLDivElement>();

onMounted(() => {
  const behaviorDesigner = new BehaviorDesigner({
    container: containerRef.value!,
    grid: {
      size: 20,
      visible: true,
      type: 'mesh',
      config: {
        color: '#ababab',
        thickness: 1,
      },
    },
    background: {
      backgroundColor: 'rgb(26,26,26)',
    },
    style: {
      anchorLine: {
        stroke: '#fff',
      },
      arrow: {
        offset: 0,
        verticalLength: 0,
      },
    },
  });
  window.behaviorDesigner = behaviorDesigner;
  behaviorDesigner.register(BaseBehaviorConnection);
  behaviorDesigner.register(Entry);
  behaviorDesigner.setDefaultEdgeType('BaseBehaviorConnection');

  behaviorDesigner.on('edge:add', ConnectionManager.onConnectionAdd);

  behaviorDesigner.on('node:click', onNodeSelectionChange);
  behaviorDesigner.on('node:delete', onNodeSelectionChange);
  behaviorDesigner.on('node:add', () => {
    setTimeout(() => {
      onNodeSelectionChange();
    }, 0);
  });

  behaviorDesigner.on('blank:click', onNodeSelectionChange);

  SceneManager.init();
});

onBeforeUnmount(() => {
  const { behaviorDesigner } = window;
  if (behaviorDesigner) {
    behaviorDesigner.off('edge:add', ConnectionManager.onConnectionAdd);
  }
  SceneManager.dispose();
});

/**
 * 节点选中变化回调
 */
const onNodeSelectionChange = () => {
  if (!window.behaviorDesigner) {
    return;
  }
  const { nodes } = window.behaviorDesigner.getSelectElements();
  console.log('nodeSelected', nodes);
  emits('nodeSelected', nodes.length ? nodes[0] : null);
};
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  background-color: rgba(0, 0, 0, 0.2);
  box-sizing: border-box;
}
.btn {
  margin-top: 20px;
}
</style>
